
var AddressBookController = function($scope, $http){
	
	$http.defaults.headers.post["Content-Type"] = "application/json";
	var urlBase="http://localhost:8080/angularjs";
	
	$scope.editMode = false;
	$scope.id = '';
	
	$scope.addAddressBook = function(ab){
		$scope.resetError();
		$http.post(urlBase + '/address/add', ab).success(function(respone){
			$scope.resetAddressBookField();
			$scope.getAllAddressBook();
		}).error(function(){
			$scope.setError("Couldn't add entry address book");
		});
	}
	
	$scope.getAllAddressBook = function(){
		$scope.resetError();
		$http.get(urlBase + '/address/all.json').success(function(respone){
			$scope.addressBooks = respone;
		}).error(function(){
			$scope.setError("Couldn't get all address books");
		});
	}
	
	$scope.editAddressBook = function(id){
		$scope.resetError();
		$http.get(urlBase + '/address/get/' + id).success(function(addressbook){
			$scope.editMode = true;
			$scope.id = addressbook.idab;
			$scope.ab = addressbook;
			$scope.getAllAddressBook();
		}).error(function(){
			$scope.setError("Couldn't edit address book");
		});
	}
	
	$scope.updateAddressBook = function(ab){
		$scope.resetError();
		ab.idab = $scope.id;
		$http.put(urlBase + '/address/update', ab).success(function(respone){
			$scope.getAllAddressBook();
			$scope.resetAddressBookField();
			$scope.editMode = false;
		}).error(function(){
			$scope.setError("Couldn't update");
		});
	}
	
	$scope.deleteAddressBook = function(id){
		$scope.resetError();
		$http.delete(urlBase + '/address/delete/' + id).success(function(respone){
			$scope.getAllAddressBook();
		}).error(function(){
			$scope.setError("Couldn't delete");
		});
	}
	
	$scope.deleteAllAddressBook = function(){
		$scope.setError();
		$http.delete(urlBase + '/address/deleteAll').success(function(respone){
			$scope.getAllAddressBook();
		}).error(function(){
			$scope.setError("Couldn't delete all");
		});
	}
	
	$scope.setError = function(message){
		$scope.error = true;
		$scope.errorMessage = message;
	}
	
	$scope.resetError = function(){
		$scope.error = false;
		$scope.errorMessage = '';
	}
	
	$scope.resetAddressBookField = function(){
		$scope.resetError();
		$scope.ab.fistname = '';
		$scope.ab.lastname = '';
		$scope.ab.phone = '';
		$scope.ab.email = '';
	}
	
	$scope.getAllAddressBook();
	
}